package com.ruoyi.web.controller.fenxi;

import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.CacheUtils;
import com.ruoyi.common.utils.PropertiesUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.RData;
import com.ruoyi.system.domain.RDataDetail;
import com.ruoyi.system.mapper.RDataDetailMapper;
import com.ruoyi.system.service.IRDataDetailService;
import com.ruoyi.system.service.IRDataService;
import com.ruoyi.web.controller.fenxi.response.R;
import com.ruoyi.web.controller.fenxi.utils.ImportUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 样本管理Controller
 * 
 * @author ruoyi
 * @date 2022-09-25
 */
@Controller
@RequestMapping("/system/data")
public class RDataController extends BaseController
{
    private String prefix = "system/data";

    @Autowired
    private IRDataService rDataService;

    @Autowired
    private IRDataDetailService rDataDetailService;
    @Autowired
    private IRDataDetailService irDataDetailService;

//    @RequiresPermissions("system:data:view")
    @GetMapping()
    public String data()
    {
        return prefix + "/data";
    }

    /**
     * 查询样本管理列表
     */
//    @RequiresPermissions("system:data:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(RData rData)
    {
        startPage();
        List<RData> list = rDataService.selectRDataList(rData);
        return getDataTable(list);
    }

    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo glist(RData rData)
    {
        startPage(1,20);
        List<RData> list1 = new ArrayList<>();
        List<RData> list = (List<RData>) CacheUtils.get(CacheUtils.RDATA_KEY);
        if(Objects.isNull(list)||list.isEmpty()){
            list =  rDataService.selectRDataList(rData);
            for (RData data : list) {
                RDataDetail rDataDetail = new RDataDetail ();
//                rDataDetail.setParentId(data.getId());
                startPage(1,20);
                List<RDataDetail> rDataDetails = rDataDetailService.selectRDataDetailList(rDataDetail);
                if(!rDataDetails.isEmpty()){
                    for(int i=0;i<20;i++){
                        if(i==rDataDetails.size()){
                            break;
                        }
                        RDataDetail dataDetail = rDataDetails.get(i);
                        RData rData1 = new RData();
                        BeanUtils.copyProperties(data,rData1);
                        rData1.setUrl(dataDetail.getName());
                        list1.add(rData1);
                    }
                }
            }
            CacheUtils.put(CacheUtils.RDATA_KEY,list1);
        }else{
            list1 = list;
        }
        return getDataTable(list1);
    }
    /**
     * 导出样本管理列表
     */
//    @RequiresPermissions("system:data:export")
    @Log(title = "样本管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(RData rData)
    {
        List<RData> list = rDataService.selectRDataList(rData);
        ExcelUtil<RData> util = new ExcelUtil<RData>(RData.class);
        return util.exportExcel(list, "样本管理数据");
    }

    /**
     * 新增样本管理
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存样本管理
     */
//    @RequiresPermissions("system:data:add")
    @Log(title = "样本管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(RData rData)
    {

        int i = 0;
        try {
            R importsave = importsave(rData);
            if(importsave.get("code").equals(0)){
                i = 1;
            }
            CacheUtils.remove(CacheUtils.RDATA_KEY);
        }catch (Exception e){
            logger.error("添加样本失败"+e);
        }
        return toAjax(i);
    }

//    @RequiresPermissions("system:data:add")
    @Log(title = "样本管理", businessType = BusinessType.INSERT)
    @PostMapping("/addEdit")
    @ResponseBody
    public AjaxResult addEdit(RData rData)
    {

        int i = 0;
        try {
            R importsave = importsave(rData);
            if(importsave.get("code").equals(0)){
                i = 1;
            }
            CacheUtils.remove(CacheUtils.RDATA_KEY);
        }catch (Exception e){
            logger.error("添加样本失败"+e);
        }
        return toAjax(i);
    }
    /**
     * 导入完成后进行解析
     * @return
     * @throws Exception
     */
    @RequestMapping("/import")
    @ResponseBody
    public R importsave (@RequestBody RData rModel) {
        Long id = rModel.getId();
        if (id == null) {
            rDataService.insertRData(rModel);
        } else {
            rDataService.updateRData(rModel);
        }

        String path = rModel.getUrl();
        String code = rModel.getCode();
        try {
            Long userId = ShiroUtils.getUserId();
            String root = PropertiesUtils.getInstance().get("file_path");
            path = root + path.substring(path.indexOf("/images/") + 8);
            ImportUtil.getInstance().import2Data(rModel.getId(), userId, path, code);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("导入失败, 请重新导入！");
        }
        return R.ok();
    }
    /**
     * 修改样本管理
     */
//    @RequiresPermissions("system:data:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        RData rData = rDataService.selectRDataById(id);
        mmap.put("rData", rData);
        return prefix + "/edit";
    }

    /**
     * 修改样本管理
     */
//    @RequiresPermissions("system:data:edit")
    @GetMapping("/addEdit/{id}")
    public String addEdit(@PathVariable("id") Long id, ModelMap mmap)
    {
        RData rData = rDataService.selectRDataById(id);
        mmap.put("rData", rData);
        return prefix + "/addEdit";
    }

    /**
     * 修改保存样本管理
     */
//    @RequiresPermissions("system:data:edit")
    @Log(title = "样本管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(RData rData)
    {
//        int i = 0;
//        try {
//            R importsave = importsave(rData);
//            if(importsave.get("code").equals(0)){
//                i = 1;
//            }
//        }catch (Exception e){
//            logger.error("修改样本失败"+e);
//        }
        CacheUtils.remove(CacheUtils.RDATA_KEY);
        return toAjax( rDataService.updateRData(rData));

    }

    /**
     * 删除样本管理
     */
//    @RequiresPermissions("system:data:remove")
    @Log(title = "样本管理", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        Long [] idsl = Convert.toLongArray(ids);
        for (Long aLong : idsl) {
            RData rData = rDataService.selectRDataById(aLong);
            CacheUtils.remove(CacheUtils.RDATA_KEY);
            irDataDetailService.deleteRDataDetailByParentId(aLong);
        }
        return toAjax(rDataService.deleteRDataByIds(ids));
    }
}
